package cn.sun.user.service.impl;

import cn.sun.basic.util.SmsUtil;
import cn.sun.basic.util.StrUtils;
import cn.sun.user.domain.User;
import cn.sun.user.mapper.UserMapper;
import cn.sun.user.service.IUserService;
import cn.sun.user.service.IVerifyService;
import cn.sun.user.util.UserConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class VerifyServiceImpl implements IVerifyService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    @Qualifier("redisTemplate")
    private RedisTemplate redisTemplate;

    @Override
    public void sendVerifyCode(Map<String, String> params) {
        String phone = params.get("phone");
        String type = params.get("type");

        //1 校验
        //1.1 手机号不能为null
        if (!StringUtils.hasLength(phone))
            throw new RuntimeException("请输入手机号！");
        if ("register".equals(type)){ //注册
            //1.2 不能被注册
            User user = userMapper.findByPhone(phone);
            if (user!=null)
                throw new RuntimeException("用户已经被注册！");

            String businessKey = UserConstants.REGISTER_CODE_PREFIX + phone;
            sendSmsCode(businessKey);
        }else if("binder".equals(type)){ //绑定
            String businessKey = UserConstants.BINDER_CODE_PREFIX + phone;
            sendSmsCode(businessKey);
        }
    }


    private void  sendSmsCode(String businessKey){
        //2 判断原来的是否有效
        Object codeObj = redisTemplate
                .opsForValue().get(businessKey); //code:time
        String code = "";
        //2.1 如果有效
        if (codeObj!=null){
            String codeStr = (String) codeObj;
            //2.1.1 判断是否已过重发时间
            String time = codeStr.split(":")[1]; //114555558888
            long intervalTime = System.currentTimeMillis() - Long.valueOf(time);
            if (intervalTime<=1*60*1000){
                //2.1.1.1 如果没有过提示错误
                throw new RuntimeException("请勿重复发送短信验证码！");
            }
            //2.1.1.2 如果过了，就使用原来验证码
            code = codeStr.split(":")[0];
        }else{
            //2.2 如果没有
            //2.2.1 重新生成验证码
            code = StrUtils.getComplexRandomString(4);
        }
        //3 保存验证码到redis
        redisTemplate.opsForValue().set(businessKey
                ,code+":"+System.currentTimeMillis()
                ,3, TimeUnit.MINUTES);
        //4 调用短信接口发送短信
//        SmsUtil.sendMsg(phone,"您的验证码为："+code+",请在3分钟之内使用！");
        System.out.println("您的验证码为："+code+",请在3分钟之内使用！");
    }

}

